package middlebase

import (
	"bridge_viewing/apibase"
	"bridge_viewing/config"
	"bridge_viewing/dto"
	"bridge_viewing/enum"
	"bridge_viewing/global"
	"bridge_viewing/static"
	"bridge_viewing/utils"
	"github.com/gin-gonic/gin"
	"regexp"
)

func JwtAuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		baseParam := dto.BaseParam{
			RequestId: utils.GetRequestId(ctx),
			TraceId:   utils.GetTraceId(ctx),
		}
		token := ctx.GetHeader("token")
		if token == "" {
			excuseList := config.ServerGlobalConfig.JwtConfig.JwtExcuse
			for _, path := range excuseList {
				compile := regexp.MustCompile(path)
				if compile.MatchString(ctx.Request.RequestURI) {
					global.GetLogger().InfoByTrace(&baseParam, "JwtMiddleware path excuse :"+ctx.Request.RequestURI)
					ctx.Next()
					return
				}
			}
			global.GetLogger().ErrorByTrace(&baseParam, "JwtMiddleware authentication token is empty")
			apibase.Fail(ctx, enum.TokenInvalid)
			ctx.Abort()
			return
		} else {
			// 解析token
			claims, err := utils.ParseToken(token)
			if err != nil {
				global.GetLogger().ErrorByTrace(&baseParam, "JwtMiddleware authentication token is invalid :"+err.Error())
				apibase.Fail(ctx, enum.TokenInvalid)
				ctx.Abort()
				return
			} else if claims.UserId < 1 {
				global.GetLogger().ErrorByTrace(&baseParam, "JwtMiddleware authentication user_id is error : %d", claims.UserId)
				apibase.Fail(ctx, enum.TokenInvalid)
				ctx.Abort()
				return
			}
			global.GetLogger().InfoByTrace(&baseParam, "JwtMiddleware claims : %+v", claims)
			ctx.Set(static.USER_ID_KEY, claims.UserId)
		}
		ctx.Next()
	}
}
